package cn.com.agree.controller.v1;


import cn.com.agree.common.util.FileUtil;
import cn.com.agree.dto.book.CreateOrUpdateBookDTO;
import cn.com.agree.dto.book.CreateOrUpdateMackDTO;
import cn.com.agree.model.ProductDO;
import cn.com.agree.model.ProductMacDO;
import cn.com.agree.service.ProductService;
import cn.com.agree.vo.CreatedVO;
import cn.com.agree.vo.DeletedVO;
import cn.com.agree.vo.DownLoadVO;
import cn.com.agree.vo.UpdatedVO;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.core.annotation.GroupRequired;
import io.github.talelin.core.annotation.PermissionMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Positive;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author pedro@TaleLin
 * @author Juzi@TaleLin
 */
@RestController
@RequestMapping("/v1/book")
@Validated
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/{id}")
    public ProductDO getBook(@PathVariable(value = "id") @Positive(message = "{id.positive}") Integer id) {
        ProductDO product = productService.getById(id);
//        List<ProductMacDO> list = productService.getMacListByBcode(product.getBcode());
//        String marks = null;
//        if(list.size() > 0) {
//            for (ProductMacDO pro : list) {
//                marks += pro.getMark() + "\n";
//            }
////            product.setId(Integer.parseInt(marks));
//            product.setImage(marks);
//        }

        if (product == null) {
            throw new NotFoundException(10022);
        }
        return product;
    }

    //物理地址表格数据查询
    @GetMapping("/mac/{bcode}")
    public List<ProductMacDO> getMacs(@PathVariable("bcode")String bcode) {
        List<ProductMacDO> list = productService.getMacListByBcode(bcode);
        return list;
    }

    @GetMapping("")
    public List<ProductDO> getBooks() throws ParseException {
        List<ProductDO> products = productService.findAll();
        return products;
    }

    //模糊查询
    @GetMapping("/searchmore/{id}")
    public List<ProductDO> getBooksByPrimary(@PathVariable("id") String id) {
//    public List<ProductDO> getBooksByPrimary(@RequestBody @Validated CreateOrUpdateBookDTO validator) {
        ProductDO pro = new ProductDO();
        String[] data = id.split(",");
        for (int i=0;i<data.length;i++) {
            if (data[i] == "empty" || data[i].equals("empty")) {
                data[i] = "";
            }
        }
        pro.setTitle(data[0]);
        pro.setAuthor(data[1]);
        pro.setBcode(data[2]);
        pro.setProduct(data[3]);
        List<ProductDO> products = productService.getAllByMore(pro);
        return products;
    }

    @GetMapping("/search")
    public List<ProductDO> searchBook(@RequestParam(value = "q", required = false, defaultValue = "") String q) {
        List<ProductDO> products = productService.getBookByKeyword("%" + q + "%");
        return products;
    }


    @PostMapping("")
    public CreatedVO createBook(@RequestBody @Validated CreateOrUpdateBookDTO validator) {
        productService.createBook(validator);
        return new CreatedVO(12);
    }

    //新增物理地址
    @PostMapping("/mac")
    public CreatedVO createMac(@RequestBody @Validated CreateOrUpdateMackDTO validator) {
        productService.createMac(validator);

        //新增物理地址，物理地址总数加1
        ProductDO pro = productService.selectByBcode(validator.getBcode());
        pro.setCount(String.valueOf(Integer.parseInt(pro.getCount())+1));
        productService.updatePro(pro);

        return new CreatedVO(19);
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public DownLoadVO download(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //开始下载文件createBook
//        System.out.println(filePath);
//        FileSystemResource file = new FileSystemResource(filePath);
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
//        headers.add("Pragma", "no-cache");
//        headers.add("Expires", "0");
//        return ResponseEntity
//                .ok()
//                .headers(headers)
//                .contentLength(file.contentLength())
//                .contentType(MediaType.parseMediaType("application/octet-stream"))
//                .body(new InputStreamResource(file.getInputStream()));
//        return new DownLoadVO(16);

        //数据库资源名
        ProductDO product = productService.getById(Integer.parseInt(id));
        //本地资源路径
        String filePath = productService.downloadLic(product);
        File file = new File(filePath);
        // 文件名称
        String fileName = file.getName();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtil.setFileDownloadHeader(request, fileName));
        FileUtil.writeBytes(filePath, response.getOutputStream());
        return new DownLoadVO(16);
    }

//    @PutMapping("/download/{id}")
//    public DownLoadVO download(@PathVariable("id") String id) {
//        ProductDO product = new ProductDO();
//        productService.downloadLic(product);
//        return new DownLoadVO(16);
//    }

    //更新状态为过期
    @PutMapping("/over/{id}")
    public UpdatedVO updatePstatus(@PathVariable("id") @Positive(message = "{id.positive}") Integer id) {
        ProductDO book = productService.getById(id);
        if (book == null) {
            throw new NotFoundException(10022);
        }
        productService.updatePstatus(id);
        return new UpdatedVO(20);
    }

    @GetMapping("/version")
    public String[] version() {
        String[] res = new String[4];
        res[0] = String.valueOf(productService.selectCount());
        String[] less = productService.selectListByOvertimeLess();
        res[1] = less[0];
        if(Integer.parseInt(less[0]) == 0){
            res[3] = "。";
        }else{
            res[3] = "，客户名称为：" + less[1].substring(0,less[1].length()-1) + "，请联系及时添加!";
        }
        res[2]= String.valueOf(productService.selectByOvertimeOver());
        return  res;
    }

    //更新版本
    @PutMapping("/{id}")
    public UpdatedVO updateBook(@PathVariable("id") @Positive(message = "{id.positive}") Integer id, @RequestBody @Validated CreateOrUpdateBookDTO validator) {
        ProductDO product = productService.getById(id);
        if (product == null) {
            throw new NotFoundException(10022);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String now = sdf.format(new Date());
        try {
            long nowtime = sdf.parse(now).getTime();
            long lasttime = validator.getOverTime().getTime();
            if(lasttime >= nowtime){
                validator.setPstatus("0");
            }else{
                validator.setPstatus("2");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        productService.updateBook(product, validator);
        return new UpdatedVO(13);
    }

    //更新物理地址
    @PutMapping("/mac/{id}")
    public UpdatedVO updateMac(@PathVariable("id") @Positive(message = "{id.positive}") Integer id, @RequestBody @Validated CreateOrUpdateMackDTO validator) {
        ProductMacDO product = productService.getByMacId(id);
        if (product == null) {
            throw new NotFoundException(10022);
        }

        productService.updateMac(product, validator);
        return new UpdatedVO(18);
    }


    @DeleteMapping("/{id}")
    @GroupRequired
    @PermissionMeta(value = "删除版本", module = "版本")
    public DeletedVO deleteBook(@PathVariable("id") @Positive(message = "{id.positive}") Integer id) {
        ProductDO book = productService.getById(id);
        if (book == null) {
            throw new NotFoundException(10022);
        }
        productService.deleteById(book.getId());
        System.out.println(new DeletedVO(14));
        return new DeletedVO(14);
    }

    @DeleteMapping("/mac/{id}")
    @GroupRequired
    @PermissionMeta(value = "删除物理地址", module = "物理地址")
    public DeletedVO deleteMac(@PathVariable("id") @Positive(message = "{id.positive}") Integer id) {
        ProductMacDO promac = productService.getByMacId(id);
        productService.deleteMacById(id);
        System.out.println(new DeletedVO(17));

        //物理地址总数-1
        ProductDO pro = productService.selectByBcode(promac.getBcode());
        pro.setCount(String.valueOf(Integer.parseInt(pro.getCount())-1));
        productService.updatePro(pro);

        return new DeletedVO(17);
    }


}
